<?php

/**
 *    买家的订单管理控制器
 *
 *    @author    bansen 2015-05-21
 *    @usage    none
 */
class Seller_orderApp extends StoreadminbaseApp
{

    function index()
    {
        /* 获取订单列表 */
        $this->_get_orders();
        $this->assign('gets', $_GET);

        //vdump($minfo);
        /* 当前位置 */
        switch ($_GET['type'])
        {
            case 'all_orders':
                $lg = LANG::get('all_order');
                break;
            case 'pending':
                $lg = LANG::get('pending');
                break;
            case 'accepted':
                $lg = LANG::get('accepted');
                break;
            case 'shipped':
                $lg = LANG::get('shipped');
                break;
            case 'finished':
                $lg = LANG::get('finished');
                break;
            case 'canceled':
                $lg = LANG::get('canceled');
                break;
            case 'evalua':
                $lg = LANG::get('evalua');
                break;
            default:
                $lg = LANG::get('all_order');
        }
        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('sale_goods'), 'index.php?app=seller_order', $lg);

        /* 卖家提醒：待付款、待确认、待评价订单数 */
        $order_mod = & m('order');
        $returns_mod = & m('returns');
        $sql = "SELECT 
                count(case when status = '" . ORDER_PENDING . "' then order_id end) submitted,
                count(case when status = '" . ORDER_SHIPPED . "' then order_id end) shipped,
                count(case when status = '" . ORDER_ACCEPTED . "' then order_id end) accepted
                FROM {$order_mod->table} where seller_id = '{$_SESSION['user_info']['user_id']}'";
        $seller_stat = $order_mod->getRow($sql);
        $sql11 = "SELECT COUNT(returns_id) FROM {$returns_mod->table} WHERE seller_id = '{$_SESSION['user_info']['user_id']}' AND status IN (1,3,4,5,6,7)";
        $seller_stat['returns'] = $returns_mod->getOne($sql11);
        $this->assign('seller_stat', $seller_stat);
        /* 当前用户中心菜单 */
        $type = (isset($_GET['type']) && $_GET['type'] != '') ? trim($_GET['type']) : 'all_orders';
        $this->_curitem('order_manage');
        $this->_curmenu($type);
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('order_manage'));
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.ui/i18n/' . i18n_code() . '.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => '',
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));
        $this->_curitem('sale_goods');
        /* 显示订单列表 */
        $this->display('seller_order.index.html');
        //$this->display('seller_order.index_bak.html');
    }

    //评价管理
    function evalua()
    {
        $model_comment = & m('comment');
        $page = $this->_get_page();    //获取分页信息
        $evalua_goods = $model_comment->find(array(
            'join' => 'has_order,has_ordergoods',
            'fields' => 'comment.comment_id, comment.order_id, comment.goods_id, comment.comment, comment.evaluation, comment.add_time, comment.is_edit, order.order_sn, order.buyer_name, ordergoods.goods_name',
            'conditions' => 'comment.order_id=order_goods.order_id AND comment.comment_type=0 AND comment.is_valid =1 AND comment.to_user_id =' . $this->visitor->get('user_id'),
            'count' => true,
            'order' => 'comment.is_edit ASC, comment.add_time DESC',
            'limit' => $page['limit'],
        ));
        $page['item_count'] = $model_comment->getCount();   //获取统计的数据
        $this->_format_page($page);

        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('review'), 'index.php?app=seller_order&act=evalua', LANG::get('评价列表'));
        $this->_curitem('review');
        $this->assign('evalua_goods', $evalua_goods);
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('review'));
        $this->display('seller_evalua.index.html');
    }

    /**
     *    查看订单详情
     *
     *    @author    Garbin
     *    @return    void
     */
    function view()
    {
        $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);

        $model_order = & m('order');
        $order_info = $model_order->get(array(
            'fields' => "*, order.add_time as order_add_time",
            'conditions' => "order_id={$order_id} AND seller_id=" . $this->visitor->get('user_id'),
            'join' => 'belongs_to_store',
        ));
        if (!$order_info)
        {
            $this->show_warning('no_such_order');

            return;
        }
        include(ROOT_PATH . '/includes/cfg_status.php');
        //获取买家信息
        $orderextm_mod = & m('orderextm');
        $order_info['orderextm_info'] = $orderextm_mod->get_info($order_id);
        //获取卖家发货地址
        $selleraddress_mod = & m('selleraddress');
        $order_info['seller_address_info'] = $selleraddress_mod->get(array(
            'fields' => 'phone_mob,phone_tel,region_name,address',
            'conditions' => 'user_id=' . $order_info['seller_id'] . ' and type=0',
            'order' => 'is_deafult desc',
            'limit' => '1',
        ));

        /* 团购信息 */
        $this->_get_group($order_info);

        /* 当前位置 */
        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=member', LANG::get('sale_goods'), 'index.php?app=seller_order', LANG::get('view_order'));

        /* 当前用户中心菜单 */
        $this->_curitem('sale_goods');
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('detail'));

        /* 调用相应的订单类型，获取整个订单详情数据 */
        $order_type = & ot($order_info['extension']);
        $order_detail = $order_type->get_order_detail($order_id, $order_info);
        $spec_ids = array();
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            empty($goods['goods_image']) && $order_detail['data']['goods_list'][$key]['goods_image'] = Conf::get('default_goods_image');
            $spec_ids[] = $goods['spec_id'];
        }

        /* 查出最新的相应的货号 */
        $model_spec = & m('goodsspec');
        $spec_info = $model_spec->find(array(
            'conditions' => "spec_id" . db_create_in($spec_ids),
            'fields' => 'sku',
        ));
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            $order_detail['data']['goods_list'][$key]['sku'] = $spec_info[$goods['spec_id']]['sku'];
            $order_detail['data']['goods_list'][$key]['total_money'] = $goods['quantity'] * $goods['price'];
        }

        if ($order_info['status'] == ORDER_ACCEPTED)
        {
            $this->_split_tel($order_info['orderextm_info']);
            $this->_get_regions();
        }

        $orderStatus = array(1 => 11, 2 => 20, 3 => 30, 4 => 40);
        $showProgress = in_array($order_info['status'], $orderStatus);
        $progressId = array_search($order_info['status'], $orderStatus);
        //vdump($order_info);
        $this->assign('order', $order_info);
        $this->assign($order_detail['data']);
        $this->assign('cfg_shipping_kuaidi', $cfg_shipping_kuaidi);
        $this->assign('progressId', $progressId);
        $this->assign('showProgress', $showProgress);
        $this->assign('left_time', $this->_get_time_by_status($order_info));
        $this->_import_source();
        $this->display('seller_order.view.html');
    }

    /**
     *    收到货款
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function received_pay()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(ORDER_PENDING);
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->display('seller_order.received_pay.html');
        }
        else
        {
            $model_order = & m('order');
            $model_order->edit(intval($order_id), array('status' => ORDER_ACCEPTED, 'pay_time' => gmtime()));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            #TODO 发邮件通知
            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_ACCEPTED),
                'remark' => strip_tags($_POST['remark']),
                'log_time' => gmtime(),
            ));

            /* 发送给买家邮件，提示等待安排发货 */
//            $model_member = & m('member');
//            $buyer_info = $model_member->get($order_info['buyer_id']);
            $model_usersafety = & m('usersafety');
            $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
            $mail = get_mail('tobuyer_offline_pay_success_notify', array('order' => $order_info));
            if($buyer_info['binding_email']){
                $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }

            $new_data = array(
                'status' => Lang::get('order_accepted'),
                'actions' => array(
                    'cancel',
                    'shipped'
                ), //可以取消可以发货
            );

            $this->pop_warning('ok');
        }
    }

    /**
     *    货到付款的订单的确认操作
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function confirm_order()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(ORDER_SUBMITTED);
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->display('seller_order.confirm.html');
        }
        else
        {
            $model_order = & m('order');
            $model_order->edit($order_id, array('status' => ORDER_ACCEPTED));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_ACCEPTED),
                'remark' => strip_tags($_POST['remark']),
                'log_time' => gmtime(),
            ));

            /* 发送给买家邮件，订单已确认，等待安排发货 */
//            $model_member = & m('member');
//            $buyer_info = $model_member->get($order_info['buyer_id']);
            $model_usersafety = & m('usersafety');
            $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
            $mail = get_mail('tobuyer_confirm_cod_order_notify', array('order' => $order_info));
            if($buyer_info['binding_email']){
                $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }

            $new_data = array(
                'status' => Lang::get('order_accepted'),
                'actions' => array(
                    'cancel',
                    'shipped'
                ), //可以取消可以发货
            );

            $this->pop_warning('ok');
            ;
        }
    }

    /**
     *    调整费用
     *
     *    @author    Garbin
     *    @return    void
     */
    function adjust_fee()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(array(ORDER_SUBMITTED, ORDER_PENDING));
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        $model_order = & m('order');
        $model_orderextm = & m('orderextm');
        $shipping_info = $model_orderextm->get($order_id);
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->assign('shipping', $shipping_info);
            $this->display('seller_order.adjust_fee.html');
        }
        else
        {
            /* 配送费用 */
            $shipping_fee = isset($_POST['shipping_fee']) ? abs(floatval($_POST['shipping_fee'])) : 0;
            /* 折扣金额 */
            $goods_amount = isset($_POST['goods_amount']) ? abs(floatval($_POST['goods_amount'])) : 0;
            /* 平台免邮 */
            $free_shipping = isset($_POST['free_shipping']) ? abs(floatval($_POST['free_shipping'])) : 0;
            /* 平台让利 */
            $discount = isset($_POST['discount']) ? abs(floatval($_POST['discount'])) : 0;
            
            //平台免邮
            if($free_shipping > 0){
                $shipping_fee = $free_shipping;
            }
            
            if($goods_amount - $discount < 0){
                $this->pop_warning('优惠金额不能大于商品总价');
                return;
            }
            
            //平台优惠
            $wl_free = $free_shipping + $discount;
            /* 订单实际总金额 */
            $order_amount = round($goods_amount + $shipping_fee - $wl_free, 2);
            if ($order_amount <= 0)
            {
                /* 若商品总价＋配送费用扣队折扣小于等于0，则不是一个有效的数据 */
                $this->pop_warning('invalid_fee');
                return;
            }
            $data = array(
                'goods_amount' => $goods_amount, //修改商品总价
                'order_amount' => $order_amount, //修改订单实际总金额
                'discount' => $discount, //修改订单实际总金额
                'pay_alter' => 1    //支付变更
            );

            if ($shipping_fee != $shipping_info['shipping_fee'] || $free_shipping != $shipping_info['free_shipping'])
            {
                /* 若运费有变，则修改运费 */

                $model_extm = & m('orderextm');
                $model_extm->edit($order_id, array('shipping_fee' => $shipping_fee, 'free_shipping' => $free_shipping));
            }

            $model_order->edit($order_id, $data);
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $remark = Lang::get('adjust_fee');
            $free_shipping > 0 && $remark .= "-平台免邮({$free_shipping})";
            $discount > 0 && $remark .= "-平台让利({$discount})";
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status($order_info['status']),
                'remark' => $remark,
                'log_time' => gmtime(),
            ));

            /* 发送给买家邮件通知，订单金额已改变，等待付款 */
//            $model_member = & m('member');
//            $buyer_info = $model_member->get($order_info['buyer_id']);
            $model_usersafety = & m('usersafety');
            $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
            $mail = get_mail('tobuyer_adjust_fee_notify', array('order' => $order_info));
            if($buyer_info['binding_email']){
                $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }

            $new_data = array(
                'order_amount' => price_format($order_amount),
            );
            $this->pop_warning('ok');
        }
    }

    /**
     *    待发货的订单发货
     *
     *    @author    Garbin
     *    @return    void
     */
    function shipped()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(array(ORDER_ACCEPTED, ORDER_SHIPPED));
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        include(ROOT_PATH . '/includes/cfg_status.php');
        $model_order = & m('order');
        $model_orderextm = & m("orderextm");
        $model_returns = & m('returns');
        $order_returns = $model_returns->order_returns($order_id);

        if (!IS_POST)
        {
            /* 显示发货表单 */
            header('Content-Type:text/html;charset=' . CHARSET);
            $orderextm = $model_orderextm->get(array(
                'conditions' => "order_id = '{$order_id}'",
                'fields' => 'shipping_name'
            ));

            $shipping_names = $this->_get_shipping_names();
            $this->assign('other', false);
            if ($orderextm && !in_array($orderextm['shipping_name'], $shipping_names))
                $this->assign('other', true);
            $this->assign('order', $order_info);
            $this->assign('order_returns', $order_returns);
            $this->assign('orderextm', $orderextm);
            $this->assign('cfg_shipping_kuaidi', $cfg_shipping_kuaidi);
            $this->display('seller_order.shipped.html');
        }
        else
        {
            $shipping_name = empty($_POST['their']) ? $_POST['express'] : '自提';
            $invoice_no = empty($_POST['their']) ? html_script($_POST['invoice_no']) : '自提';
            $shipping_code = isset($cfg_shipping_kuaidi[$shipping_name]) ? $cfg_shipping_kuaidi[$shipping_name] : '';

            if (!$invoice_no)
            {
                $this->pop_warning('invoice_no_empty');
                return;
            }
            if (!$shipping_name)
            {
                $this->pop_warning('请选择物流公司');
                return;
            }

            $edit_data = array('status' => ORDER_SHIPPED, 'invoice_no' => $invoice_no);
            $is_edit = true;
            if (empty($order_info['invoice_no']))
            {
                /* 不是修改发货单号 */
                $edit_data['ship_time'] = gmtime();
                $is_edit = false;
            }
            $model_order->edit(intval($order_id), $edit_data);
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            $model_orderextm->edit(intval($order_id), array('shipping_name' => html_script(trim($shipping_name)),'shipping_code' => $shipping_code));
            if ($model_orderextm->has_error())
            {
                $this->pop_warning($model_orderextm->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_SHIPPED),
                'remark' => $_POST['remark'],
                'log_time' => gmtime(),
            ));

            $new_data = array(
                'status' => Lang::get('order_shipped'),
                'actions' => array(
                    'cancel',
                    'edit_invoice_no'
                ), //可以取消可以发货
            );
            if ($order_info['payment_code'] == 'cod')
            {
                $new_data['actions'][] = 'finish';
            }

            //关闭退货退款申请
            $this->_close_returns($order_id);

            if($shipping_name != '自提')
            {
                /* 发送给买家订单已发货通知 */
                $model_usersafety = & m('usersafety');
                $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
                $order_info['invoice_no'] = $edit_data['invoice_no'];
                $mail = get_mail('tobuyer_shipped_notify', array('order' => $order_info));
                if($buyer_info['binding_email']){
                    $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
                }
                //发送手机短信
                $model_order_extm = & m('orderextm');
                $mobile = $model_order_extm->get_fields_name($order_id, 'phone_mob');
                if (!empty($mobile))
                {
                    $msg = '尊敬的会员，您的订单' . $order_info['order_sn'] . '已发货，物流公司：' . $shipping_name . '，物流单号：' . $edit_data['invoice_no'] . '，货物正飞奔到您身边，请注意查收。';
                    include(ROOT_PATH . '/includes/sendsms/ueswt.php');
                    $gckj = new ueswt();
                    $gckj->send_sms($msg, $mobile);
                }
            }

            $backUrl = isset($_GET['ajax']) ? "" : "index.php?app=seller_order&act=view&order_id={$order_id}";
            $this->pop_warning('ok', '', $backUrl);
        }
    }

    /*
     * 修改收货地址
     * @author    libaoling
     * @return    void
     */

    public function edit_address()
    {
        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
        if (!$order_id)
        {
            $this->show_warning('no_such_order');
            return;
        }
        if (!$_POST['consignee'] || !$_POST['region_name'] || !$_POST['address'] || (!$_POST['phone_mob'] && !$_POST['phone_code']))
        {
            $this->show_warning('数据不完整!请重新填写!');
            return;
        }

        if ((!is_mobile($_POST['phone_mob']) && $_POST['phone_mob']) || (!is_zipcode($_POST['zipcode']) && $_POST['zipcode']))
        {
            $this->show_warning('format_error');
            return;
        }

        $data = array(
            'consignee' => html_script(trim($_POST['consignee'])),
            'region_id' => (int) $_POST['region_id'],
            'region_name' => html_script(trim($_POST['region_name'])),
            'address' => html_script(trim($_POST['address'])),
            'zipcode' => html_script(trim($_POST['zipcode'])),
            'phone_mob' => html_script(trim($_POST['phone_mob'])),
        );
        if ($_POST['phone_code'] && $_POST['phone_section'])
        {
            if ($_POST['phone_ext'])
            {
                $data['phone_tel'] = trim($_POST['phone_section']) . '-' . trim($_POST['phone_code']) . '-' . trim($_POST['phone_ext']);
            }
            else
            {
                $data['phone_tel'] = trim($_POST['phone_section']) . '-' . trim($_POST['phone_code']);
            }
            if (!is_tel($data['phone_tel']))
            {
                $this->show_warning('电话号码不正确');
                return;
            }
        }
        else
        {
            $data['phone_tel'] = '';
        }
        $order_extm = & m("orderextm");

        $order_extm->edit($order_id, $data);
        if ($order_extm->has_error())
        {
            $this->show_warning($order_extm->get_error());
            return;
        }
        $this->pop_warning("ok", '', "index.php?app=seller_order&act=view&order_id={$order_id}");
    }

    /**
     *    取消订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function cancel_order()
    {
        /* 取消的和完成的订单不能再取消 */
        //list($order_id, $order_info)    = $this->_get_valid_order_info(array(ORDER_SUBMITTED, ORDER_PENDING, ORDER_ACCEPTED, ORDER_SHIPPED));
        $order_id = isset($_GET['order_id']) ? trim($_GET['order_id']) : '';
        if ($_REQUEST['cancel'] == 1)
        {
            $model_order = & m('order');
            $x = $model_order->edit(intval($order_id), array('status' => ORDER_CANCELED));
            /* 加回订单商品库存 */
            $ct = $model_order->change_stock('+', intval($order_id));
            $ct_arr = array();
            if ($ct == true)
            {
                $ct_arr['status'] = 1;
            }
            else
            {
                $ct_arr['status'] = 2;
            }
            $this->json_result($ct_arr);
        }
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
        }
        $status = array(ORDER_PENDING);
        $order_ids = explode(',', $order_id);
        if ($ext)
        {
            $ext = ' AND ' . $ext;
        }

        $model_order = & m('order');
        /* 只有已发货的货到付款订单可以收货 */
        $order_info = $model_order->find(array(
            'conditions' => "order_id" . db_create_in($order_ids) . " AND seller_id=" . $this->visitor->get('manage_store') . " AND status " . db_create_in($status) . $ext,
        ));
        $ids = array_keys($order_info);
        if (!$order_info)
        {
            echo Lang::get('没有该订单或该订单不可取消');
            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('orders', $order_info);
            $this->assign('order_id', count($ids) == 1 ? current($ids) : implode(',', $ids));
            $this->display('seller_order.cancel.html');
        }
        else
        {
            $model_order = & m('order');
            foreach ($ids as $val)
            {
                $id = intval($val);
                $model_order->edit($id, array('status' => ORDER_CANCELED));

                if ($model_order->has_error())
                {
                    //$_erros = $model_order->get_error();
                    //$error = current($_errors);
                    //$this->json_error(Lang::get($error['msg']));
                    //return;
                    continue;
                }

                /* 加回订单商品库存 */
                $model_order->change_stock('+', $id);
                $cancel_reason = (!empty($_POST['remark'])) ? strip_tags($_POST['remark']) : $_POST['cancel_reason'];
                /* 记录订单操作日志 */
                $order_log = & m('orderlog');
                $order_log->add(array(
                    'order_id' => $id,
                    'operator' => addslashes($this->visitor->get('user_name')),
                    'order_status' => order_status($order_info[$id]['status']),
                    'changed_status' => order_status(ORDER_CANCELED),
                    'remark' => $cancel_reason,
                    'log_time' => gmtime(),
                ));

                /* 发送给买家订单取消通知 */
//                $model_member = & m('member');
//                $buyer_info = $model_member->get($order_info[$id]['buyer_id']);
                $model_usersafety = & m('usersafety');
                $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
                $mail = get_mail('tobuyer_cancel_order_notify', array('order' => $order_info[$id], 'reason' => $_POST['remark']));
                if($buyer_info['binding_email']){
                    $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
                }

                $new_data = array(
                    'status' => Lang::get('order_canceled'),
                    'actions' => array(), //取消订单后就不能做任何操作了
                );
            }
            $this->pop_warning('ok');
        }
    }

    /**
     *    完成交易(货到付款的订单)
     *
     *    @author    Garbin
     *    @return    void
     */
    function finished()
    {
        list($order_id, $order_info) = $this->_get_valid_order_info(ORDER_SHIPPED, 'payment_code=\'cod\'');
        if (!$order_id)
        {
            echo Lang::get('no_such_order');
            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            /* 当前用户中心菜单 */
            $this->_curitem('seller_order');
            /* 当前所处子菜单 */
            $this->_curmenu('finished');
            $this->assign('_curmenu', 'finished');
            $this->assign('order', $order_info);
            $this->display('seller_order.finished.html');
        }
        else
        {
            $now = gmtime();
            $model_order = & m('order');
            $model_order->edit($order_id, array('status' => ORDER_FINISHED, 'pay_time' => $now, 'finished_time' => $now));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());
                return;
            }

            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark' => $_POST['remark'],
                'log_time' => gmtime(),
            ));

            /* 更新累计销售件数 */
            $model_goodsstatistics = & m('goodsstatistics');
            $model_ordergoods = & m('ordergoods');
            $order_goods = $model_ordergoods->find("order_id={$order_id}");
            foreach ($order_goods as $goods)
            {
                $model_goodsstatistics->edit($goods['goods_id'], "sales=sales+{$goods['quantity']}");
            }


            /* 发送给买家交易完成通知，提示评论 */
//            $model_member = & m('member');
//            $buyer_info = $model_member->get($order_info['buyer_id']);
            $model_usersafety = & m('usersafety');
            $buyer_info = $model_usersafety->get("user_id='{$order_info['buyer_id']}'");
            $mail = get_mail('tobuyer_cod_order_finish_notify', array('order' => $order_info));
            if($buyer_info['binding_email']){
                $this->_mailto($buyer_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }

            $new_data = array(
                'status' => Lang::get('order_finished'),
                'actions' => array(), //完成订单后就不能做任何操作了
            );

            $this->pop_warning('ok');
        }
    }

    /**
     *    获取有效的订单信息
     *
     *    @author    Garbin
     *    @param     array $status
     *    @param     string $ext
     *    @return    array
     */
    function _get_valid_order_info($status, $ext = '')
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {
            return array();
        }
        if (!is_array($status))
        {
            $status = array($status);
        }

        if ($ext)
        {
            $ext = ' AND ' . $ext;
        }

        $model_order = & m('order');
        /* 只有已发货的货到付款订单可以收货 */
        $order_info = $model_order->get(array(
            'conditions' => "order_id={$order_id} AND seller_id=" . $this->visitor->get('manage_store') . " AND status " . db_create_in($status) . $ext,
        ));
        if (empty($order_info))
        {
            return array();
        }

        return array($order_id, $order_info);
    }

    /**
     *    获取订单列表
     *
     *    @author    Garbin
     *    @return    void
     */
    function _get_orders()
    {
        $page = $this->_get_page(10);
        $model_order = & m('order');
        $type = isset($_GET['type']) ? html_script($_GET['type']) : 'all_orders';

        $time_hh_list = array(
            '00'=>'00','01'=>'01','02'=>'02','03'=>'03','04'=>'04','05'=>'05','06'=>'06','07'=>'07',
            '08'=>'08','09'=>'09','10'=>'10','11'=>'11','12'=>'12','13'=>'13','14'=>'14','15'=>'15','16'=>'16','17'=>'17','18'=>'18','19'=>'19','20'=>'20',
            '21'=>'21','22'=>'22','23'=>'23'
        );

        $query = $_GET;
        $query['search_name'] = html_script($query['search_name']);
        $query['order_sn'] = html_script($query['order_sn']);
        $query['goods_name'] = html_script($query['goods_name']);
        if($type != 'all_orders' && !empty($type))
        {
            $conditions = " AND status=".order_status_translator($type);
        }
        else
        {
            $conditions = $this->_condition_by_params();
        }

        // 团购订单
        /*if (!empty($_GET['group_id']) && intval($_GET['group_id']) > 0)
        {
            $groupbuy_mod = &m('groupbuy');
            $order_ids = $groupbuy_mod->get_order_ids(intval($_GET['group_id']));
            $order_ids && $conditions .= ' AND order_alias.order_id' . db_create_in($order_ids);
        }*/

        if($conditions !== false)
        {
            /* 查找订单 */
            $orders = $model_order->findAll(array(
                'conditions' => "seller_id=" . $this->visitor->get('manage_store') . "{$conditions}",
                'fields' => 'this.*,orderextm.shipping_fee,orderextm.consignee,orderextm.free_shipping,orderextm.shipping_code',
                'count' => true,
                'join' => 'has_orderextm',
                'limit' => $page['limit'],
                'order' => 'add_time DESC',
                'include' => array(
                    'has_ordergoods', //取出商品
                ),
            ));

            $spec_ids = array();
            foreach ($orders as $key1 => $order)
            {
                if($order['free_shipping'] > 0 || $order['discount'] > 0){
                    $orders[$key1]['old_order_amount'] = $order['goods_amount'] + $order['shipping_fee'];
                }
                if (isset($order['order_goods']) && is_array($order['order_goods']))
                    foreach ($order['order_goods'] as $key2 => $goods)
                    {
                        $spec_ids[] = $goods['spec_id'];
                    }
            }

            /* 查出最新的相应的货号 */
            $model_spec = & m('goodsspec');
            $spec_info = $model_spec->find(array(
                'conditions' => "spec_id " . db_create_in($spec_ids),
                'fields' => 'sku',
            ));

            foreach ($orders as $key1 => $order)
            {
                if (isset($order['order_goods']) && is_array($order['order_goods']))
                {
                    $ak = array_keys($order['order_goods']);
                    $orders[$key1]['index'] = $ak[0];
                    $orders[$key1]['endtime'] = date('m/d/Y H:s:m', $order['add_time'] + 3 * 24 * 3600);
                    foreach ($order['order_goods'] as $key2 => $goods)
                    {
                        empty($goods['goods_image']) && $orders[$key1]['order_goods'][$key2]['goods_image'] = Conf::get('default_goods_image');
                        $orders[$key1]['order_goods'][$key2]['sku'] = $spec_info[$goods['spec_id']]['sku'];
                    }
                    $orders[$key1]['is_mobile'] = (strpos($order['payment_code'], "wap") !== false) ? true : false;
                }
            }

            $page['item_count'] = $model_order->getCount();
        }

        $this->_format_page($page);
        $this->assign('order_status_list', array(
            ORDER_PENDING => '待付款',
            ORDER_ACCEPTED => '待发货',
            ORDER_SHIPPED =>  '待确认收货',
            ORDER_FINISHED => '交易成功',
            ORDER_CANCELED => '交易取消',
            ORDER_CLOSED =>   '交易关闭',
        ));
        $this->assign('evaluation_status_list', array(
            '0' => '未被评价',
            '1' => '已被评价',
        ));
        $this->assign('type', $type);
        $this->assign('query', $query);
        $this->assign('time_hh_list', $time_hh_list);
        $this->assign('orders', $orders);
        $this->assign('page_info', $page);
    }

    //搜索查询条件
    function _condition_by_params()
    {
        $condition = "";
        if($_GET['status'] !== '' && isset($_GET['status']))
        {
            $condition .= " AND status =" . intval($_GET['status']);
        }
        if($_GET['evaluation_status'] !== '' && isset($_GET['evaluation_status']))
        {
            $condition .= " AND evaluation_status =" . intval($_GET['evaluation_status']);
        }
        if(!empty($_GET['search_name']))
        {
            $condition .= " AND (buyer_name LIKE '%".html_script($_GET['search_name'])."%' OR consignee LIKE '%".html_script($_GET['search_name'])."%')";
        }
        if(!empty($_GET['order_sn']))
        {
            $condition .= " AND order_sn LIKE '%".html_script($_GET['order_sn'])."%'";
        }
        if(!empty($_GET['add_time_from_date']))
        {
            $add_time_from_ii = !empty($_GET['add_time_from_ii']) ? intval($_GET['add_time_from_ii']) : '00';
            $add_time_from = trim($_GET['add_time_from_date']).' '.$_GET['add_time_from_hh'].':'.$add_time_from_ii.':00';
            $condition .= " AND add_time >=" . gmstr2time($add_time_from);
        }
        if(!empty($_GET['add_time_to_date']))
        {
            $add_time_to_ii = !empty($_GET['add_time_to_ii']) ? intval($_GET['add_time_to_ii']) : '00';
            $add_time_to = trim($_GET['add_time_to_date']).' '.$_GET['add_time_to_hh'].':'.$add_time_to_ii.':00';
            $condition .= " AND add_time <" . gmstr2time($add_time_to);
        }
        if(!empty($_GET['goods_name']))
        {
            $condition1 = " goods_name LIKE '%".html_script($_GET['goods_name'])."%' OR sku LIKE '%".html_script($_GET['goods_name'])."%'";
            $ordergoods_mod =& m('ordergoods');
            $sql = "select distinct og.order_id from {$ordergoods_mod->table} og left join ".DB_PREFIX."goods_spec gs on og.spec_id=gs.spec_id where {$condition1}";
            $order_ids = $ordergoods_mod->getCol($sql);
            if(is_array($order_ids))
            {
                $condition .= ' AND order_alias.order_id' . db_create_in($order_ids);
            }
            else
            {
                return false;
            }
        }

        return $condition;
    }

    /* 三级菜单 */

    function _get_member_submenu()
    {
        $array = array(
            array(
                'name' => 'all_orders',
                'url' => 'index.php?app=seller_order&amp;type=all_orders',
            ),
            array(
                'name' => 'pending',
                'url' => 'index.php?app=seller_order&amp;type=pending',
            ),
            array(
                'name' => 'submitted',
                'url' => 'index.php?app=seller_order&amp;type=submitted',
            ),
            array(
                'name' => 'accepted',
                'url' => 'index.php?app=seller_order&amp;type=accepted',
            ),
            array(
                'name' => 'shipped',
                'url' => 'index.php?app=seller_order&amp;type=shipped',
            ),
            array(
                'name' => 'finished',
                'url' => 'index.php?app=seller_order&amp;type=finished',
            ),
            array(
                'name' => 'canceled',
                'url' => 'index.php?app=seller_order&amp;type=canceled',
            ),
        );
        return $array;
    }

    private function _get_time_by_status($order)
    {
        $result = 0;
        $status = $order['status'];
        $timeStatus = array(
            11 => array('time' => 3 * 24 * 3600, 'field' => 'order_add_time'),
            30 => array('time' => 10 * 24 * 3600, 'field' => 'ship_time'),
        );

        if (in_array($status, array_keys($timeStatus)))
        {
            $result = $order[$timeStatus[$status]['field']] + $timeStatus[$status]['time'] - time();
        }
        return $result;
    }

    private function _import_source()
    {
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.ui/i18n/' . i18n_code() . '.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'mlselection.js',
                    'attr' => ''
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));
    }

    /*
     * 拆分电话号码
     */

    private function _split_tel($address)
    {
        if ($address['phone_tel'])
        {
            $phone_tel = explode('-', $address['phone_tel']);
        }
        $this->assign('phone_tel', $phone_tel);
    }

    /* 团购信息 */

    private function _get_group($order_info)
    {
        if ($order_info['extension'] == 'groupbuy')
        {
            $groupbuy_mod = &m('groupbuy');
            $group = $groupbuy_mod->get(array(
                'join' => 'be_join',
                'conditions' => 'order_id=' . $order_id,
                'fields' => 'gb.group_id',
            ));
            $this->assign('group_id', $group['group_id']);
        }
    }

    /**
     *    获取区域信息
     *
     */
    private function _get_regions()
    {
        $model_region = & m('region');
        $regions = $model_region->get_list(0);
        if ($regions)
        {
            $tmp = array();
            foreach ($regions as $key => $value)
            {
                $tmp[$key] = $value['region_name'];
            }
            $regions = $tmp;
        }
        $this->assign('regions', $regions);
    }

    private function _close_returns($order_id)
    {
        $model_order = & m('order');

        $order_info = $model_order->get(array(
            'fields' => "this.invoice_no,orderextm.shipping_name",
            'conditions' => "order_alias.order_id={$order_id}",
            'join' => 'has_orderextm',
        ));
        if (!empty($order_info))
        {
            $model_returns = & m('returns');
            $model_returns->close_returns($order_id, 2, $order_info['shipping_name'], $order_info['invoice_no']);
        }
    }

    private function _get_shipping_names()
    {
        return array(
            '顺丰快递', 'EMS快递', '圆通快递', '中通快递', '申通快递', '韵达快递', '中国邮政', '天天快递'
        );
    }

}

?>
